package com.bjpowernode.shop.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bjpowernode.shop.base.BaseProduct;
import com.bjpowernode.shop.domain.Prod;
import com.bjpowernode.shop.domain.ProdComm;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/prod/prodComm")
public class ProdCommController extends BaseProduct {

    // 查询评论列表 分页模糊查询【按商品名称模糊查询】
    @GetMapping("/page")
    public ResponseEntity<Page<ProdComm>> page(Page<ProdComm> page, String prodName, String status) {

        // 查询符合关键词的商品列表数据
        List<Prod> prodList = prodService.list(new LambdaQueryWrapper<Prod>()
                .like(StringUtils.hasText(prodName),
                        Prod::getProdName,
                        prodName
                ));

        // 若无符合商品，则直接返回空列表
        if (CollectionUtils.isEmpty(prodList))
            return ResponseEntity.ok(null);

        // 获取商品列表ids
        List<Long> prodIds = prodList.stream().map(Prod::getProdId).collect(Collectors.toList());

        // 分页查询符合条件的评论[条件=状态相等+商品id符合]
        Page<ProdComm> commPage = prodCommService.page(page, new LambdaQueryWrapper<ProdComm>()
                .eq(
                        !ObjectUtils.isEmpty(status),
                        ProdComm::getStatus,
                        status
                )
                .in(
                        ProdComm::getProdId,
                        prodIds
                )
        );

        // 从分页数据中获取评论列表
        List<ProdComm> commList = commPage.getRecords();

        // 遍历评论，准备封装商品名，一对一
        commList.forEach(
                comm -> {
                    // 将与当前评论对应的商品
                    List<Prod> relationProdList = prodList.stream().filter(
                            prod -> prod.getProdId().equals(comm.getProdId())
                    ).collect(Collectors.toList());
                    // 将商品名加入当前评论对象中
                    comm.setProdName(relationProdList.get(0).getProdName());
                }
        );
        return ResponseEntity.ok(commPage);
    }

    // 查询当前要修改的评论
    @GetMapping("/{id}")
    public ResponseEntity<ProdComm> get(@PathVariable Integer id) {
        return ResponseEntity.ok(prodCommService.getById(id));
    }

    // 修改掌柜回复内容，更新回复时间
    @PutMapping
    @Transactional
    public ResponseEntity<Boolean> update(@RequestBody ProdComm prodComm) {
        return ResponseEntity.ok(prodCommService.saveOrUpdate(
                prodComm.setReplySts(1).setReplyTime(new Date())
        ));
    }
}